package com.peng.community.event;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.peng.community.constant.CommunityConstant;
import com.peng.community.entity.DiscussPost;
import com.peng.community.entity.Event;
import com.peng.community.entity.Message;
import com.peng.community.service.DiscussPostService;
import com.peng.community.service.impl.ElasticSearchService;
import com.peng.community.service.impl.MessageService;
import com.peng.community.util.CommunityUtils;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;

@Component
@Slf4j
public class EventConsumer implements CommunityConstant {

    @Autowired
    MessageService messageService;

    //xxx YY了 zzz （小写为人名,大写为业务类型）
    @KafkaListener(topics = {TOPIC_COMMENT, TOPIC_LIKE, TOPIC_FOLLOW})
    public void handle(ConsumerRecord consumerRecord) {
        if (consumerRecord == null || consumerRecord.value() == null) {
            log.error("消息的内容为空");
            return;
        }
        Event event = JSONObject.parseObject(consumerRecord.value().toString(), Event.class);
        if (event == null) {
            log.error("消息格式错误");
            return;
        }

        //发送站内通知
        //向数据库中插入一条Message数据
        Message message = new Message();
        message.setFromId(SYSTEM_USER_ID);
        message.setToId(event.getEntityUserId()); //被点赞的作者
        message.setConversationId(event.getTopic());
        message.setStatus(0); //默认有效
        message.setCreateTime(new Date());

        //构造消息内容，用map最方便
        Map<String, Object> content = new HashMap<>();
        content.put("entityType",event.getEntityType());
        content.put("entityId", event.getEntityId());
        content.put("userId", event.getUserId());

        Map<String, Object> data = event.getData();
        if (data != null) {
            data.forEach(content::put);
        }
        message.setContent(JSONObject.toJSONString(content));

        messageService.insertMessage(message);
    }

    @Autowired
    DiscussPostService discussPostService;

    @Autowired
    ElasticSearchService elasticSearchService;

    //监控发帖事件，将贴子发送到ES服务器
    @KafkaListener(topics = {TOPIC_PUBLISH})
    public void handlePublishMessage(ConsumerRecord consumerRecord) {
        if (consumerRecord == null || consumerRecord.value() == null) {
            log.error("消息的内容为空");
            return;
        }
        Event event = JSONObject.parseObject(consumerRecord.value().toString(), Event.class);
        if (event == null) {
            log.error("消息格式错误");
            return;
        }

        //查询post并存储到ES中
        DiscussPost discussPost = discussPostService.findDiscussPostById(event.getEntityId());
        elasticSearchService.save(discussPost);
    }

    //监控删帖事件，将贴子从ES服务器删除
    @KafkaListener(topics = {TOPIC_DELETE})
    public void handleDeleteMessage(ConsumerRecord consumerRecord) {
        if (consumerRecord == null || consumerRecord.value() == null) {
            log.error("消息的内容为空");
            return;
        }
        Event event = JSONObject.parseObject(consumerRecord.value().toString(), Event.class);
        if (event == null) {
            log.error("消息格式错误");
            return;
        }

        //查询post并存储到ES中
        DiscussPost discussPost = discussPostService.findDiscussPostById(event.getEntityId());
        elasticSearchService.delete(discussPost);
    }


    @Value("${wk.image.storage}")
    private String wkImageStorage;

    @Value("${wk.image.command}")
    private String wkImageCommand;

    @Value("${qiniu.key.access}")
    private String accessKey;

    @Value("${qiniu.key.secret}")
    private String secretKey;

    @Value("${qiniu.bucket.share.name}")
    private String shareBucketName;


    @Autowired
    ThreadPoolTaskScheduler taskScheduler;

    @KafkaListener(topics = {TOPIC_SHARE})
    public void handleShare(ConsumerRecord consumerRecord) {
        if (consumerRecord == null || consumerRecord.value() == null) {
            log.error("消息的内容为空");
            return;
        }
        Event event = JSONObject.parseObject(consumerRecord.value().toString(), Event.class);
        if (event == null) {
            log.error("消息格式错误");
            return;
        }

        String htmlUrl = (String)event.getData().get("htmlUrl");
        String fileName = (String)event.getData().get("fileName");
        String suffix = (String)event.getData().get("suffix");

        String cmd = wkImageCommand + " --quality 75 " + htmlUrl
                + " " + wkImageStorage + "/" + fileName + suffix;

        try {
            Runtime.getRuntime().exec(cmd);
            log.info("生成长图成功：{}",cmd);

            //开启定时任务，每隔500ms检查文件是否上传成功
            UploadTask uploadTask = new UploadTask(fileName, suffix);
            ScheduledFuture<?> future = taskScheduler.scheduleAtFixedRate(uploadTask, 500);
            uploadTask.setFuture(future);

        } catch (IOException e) {
            e.printStackTrace();
            log.error("生成长图失败：{}",e.getCause().toString());
        }
    }


    class UploadTask implements Runnable {

        //要上传的文件
        private String filename;
        private String suffix;
        private int uploadTimes; //上传次数
        private long startTime; //任务开始的时间，就是此Task被初始化的时间

        public void setFuture(Future future) {
            this.future = future;
        }

        private Future future;

        public UploadTask(String filename, String suffix) {
            this.filename = filename;
            this.suffix = suffix;
            this.startTime = System.currentTimeMillis();
            this.uploadTimes = 0;
        }



        @Override
        //开头提供递归出口
        public void run() {
            if (System.currentTimeMillis() - startTime > 300000) {
                //6分钟还没上传成功
                log.error("上传时间过长:{}", filename);
                future.cancel(true);
                return;
            }

            if (uploadTimes > 3) {
                //已经上传试过三次
                log.error("上传次数过多:{}", filename);
                future.cancel(true);
                return;
            }

            File file = new File(wkImageStorage + "/" + filename + suffix);
            if (file.exists()) {
                log.info("当前是第{}次上传:{}",uploadTimes,filename);

                //生成凭证，上传文件
                StringMap stringMap = new StringMap();
                stringMap.put("returnBody", CommunityUtils.toJsonString(0));
                Auth auth = Auth.create(accessKey,secretKey);
                String uploadToken = auth.uploadToken(shareBucketName, filename, 3600, stringMap);

                //指定上传的机房
                UploadManager uploadManager = new UploadManager(new Configuration(Zone.zone1()));
                try {
                    Response response = uploadManager.put(file, filename, uploadToken, null, "image/" + suffix, false);
                    JSONObject jsonObject = JSON.parseObject(response.getInfo());
                    if (jsonObject == null || !jsonObject.containsKey("code") || jsonObject.get("code").equals("0")) {
                        //返回的结果不符合预期
                        log.error("第{}次上传失败:{}", uploadTimes, filename);

                    } else {
                        log.info("第{}次上传成功:{}", uploadTimes, filename);
                        future.cancel(true);
                    }
                } catch (QiniuException e) {
                    log.error("第{}次上传失败:{}", uploadTimes, filename);
                    e.printStackTrace();
                }
            } else {
                log.error("等待图片生成:{}", filename);
            }

        }
    }


}
